<template>
  <el-dialog
    v-model="dialogVisible"
    title="创建新数据表"
    width="80%"
    :close-on-click-modal="false"
    @closed="resetForm"
  >
    <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
      <!-- 基本信息 -->
      <el-card class="form-section">
        <template #header>
          <span class="section-title">基本信息</span>
        </template>
        
        <el-form-item label="表名" prop="tableName">
          <el-input 
            v-model="form.tableName" 
            placeholder="请输入表名，如：用户信息"
            style="width: 300px;"
          />
        </el-form-item>
        
        <el-form-item label="表说明" prop="comment">
          <el-input 
            v-model="form.comment" 
            placeholder="请输入表的说明信息"
            style="width: 500px;"
          />
        </el-form-item>
      </el-card>

      <!-- 列定义 -->
      <el-card class="form-section">
        <template #header>
          <div class="section-header">
            <span class="section-title">列定义</span>
            <el-button type="primary" size="small" @click="addColumn">
              <el-icon><Plus /></el-icon>
              添加列
            </el-button>
          </div>
        </template>
        
        <el-table :data="form.columns" style="width: 100%">
          <el-table-column label="列名" width="150">
            <template #default="{ row, $index }">
              <el-input 
                v-model="row.name" 
                placeholder="列名"
                size="small"
                @blur="validateColumn($index)"
              />
            </template>
          </el-table-column>
          
          <el-table-column label="数据类型" width="120">
            <template #default="{ row }">
              <el-select v-model="row.type" placeholder="类型" size="small" style="width: 100%">
                <el-option-group
                  v-for="group in groupedDataTypes"
                  :key="group.category"
                  :label="group.category"
                >
                  <!-- <el-option
                    v-for="type in group.types"
                    :key="type.type"
                    :label="type.type"
                    :value="type.type"
                  /> -->
                  <!-- lable显示中文描述，但是值传的还是后端的type -->
                  <el-option
                    v-for="type in group.types"
                    :key="type.type"
                    :label="type.description"   
                    :value="type.type"          
                  />
                </el-option-group>
              </el-select>
            </template>
          </el-table-column>
          
          <el-table-column label="长度" width="80">
            <template #default="{ row }">
              <el-input 
                v-model="row.length" 
                placeholder="长度"
                size="small"
                :disabled="!needsLength(row.type)"
              />
            </template>
          </el-table-column>
          
          <el-table-column label="选项" width="200">
            <template #default="{ row }">
              <div class="column-options">
                <el-checkbox v-model="row.notNull" size="small">非空</el-checkbox>
              </div>
            </template>
          </el-table-column>
          
          <el-table-column label="默认值" width="120">
            <template #default="{ row }">
              <el-input 
                v-model="row.defaultValue" 
                placeholder="默认值"
                size="small"
              />
            </template>
          </el-table-column>
          
          <el-table-column label="说明" min-width="150">
            <template #default="{ row }">
              <el-input 
                v-model="row.comment" 
                placeholder="列说明"
                size="small"
              />
            </template>
          </el-table-column>
          
          <el-table-column label="操作" width="80" align="center">
            <template #default="{ $index }">
              <el-button 
                type="danger" 
                size="small" 
                @click="removeColumn($index)"
                :disabled="form.columns.length <= 1"
              >
                <el-icon><Delete /></el-icon>
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        
        <div class="column-tips" v-if="form.columns.length === 0">
          <el-empty description="暂无列定义，请点击上方按钮添加列" :image-size="80" />
        </div>
      </el-card>
    </el-form>
    
    <template #footer>
      <el-button @click="dialogVisible = false">取消</el-button>
      <el-button type="primary" @click="createTable" :loading="loading">
        <el-icon><Check /></el-icon>
        创建表
      </el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, computed, watch, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Plus, Delete, Check } from '@element-plus/icons-vue'
import { apiService } from '../api'
import { useRoute } from 'vue-router'
const route = useRoute()

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  }
})

const emit = defineEmits(['update:visible', 'success'])

const dialogVisible = computed({
  get: () => props.visible,
  set: (val) => emit('update:visible', val)
})

const formRef = ref()
const loading = ref(false)
const dataTypes = ref([])

// 表单数据
const form = reactive({
  tableName: '',
  comment: '',
  columns: []
})

// 表单验证规则
const rules = {
  tableName: [
    { required: true, message: '请输入表名', trigger: 'blur' },
    { min: 1, max: 64, message: '表名长度应在1-64个字符', trigger: 'blur' }
  ]
}

// 按类别分组的数据类型
const groupedDataTypes = computed(() => {
  const groups = {}
  dataTypes.value.forEach(type => {
    if (!groups[type.category]) {
      groups[type.category] = []
    }
    groups[type.category].push(type)
  })
  
  return Object.entries(groups).map(([category, types]) => ({
    category,
    types
  }))
})

// 判断数据类型是否需要长度
// const needsLength = (type) => {
//   const typeInfo = dataTypes.value.find(t => t.type === type)
//   return typeInfo?.needsLength || false
// }
const needsLength = (type) => {
  return type === 'ENUM'
}


// 判断数据类型是否可以自增
const canAutoIncrement = (type) => {
  return ['INT', 'BIGINT'].includes(type)
}

// 创建默认列
const createDefaultColumn = () => {
  return {
    name: '',
    type: 'VARCHAR',
    length: null,
    notNull: false,
    primaryKey: false,
    autoIncrement: false,
    defaultValue: '',
    comment: ''
  }
}

// 添加列
const addColumn = () => {
  form.columns.push(createDefaultColumn())
}

// 删除列
const removeColumn = (index) => {
  form.columns.splice(index, 1)
}

// 验证列
const validateColumn = (index) => {
  const column = form.columns[index]
  if (column.name.trim().toLowerCase() === 'id') {
    ElMessage.warning('“id” 列由系统自动生成，无需手动添加')
    column.name = ''
    return false
  }
  if (!column.name.trim()) {
    ElMessage.warning('请填写列名')
    return false
  }
  if (!column.type) {
    ElMessage.warning('请选择数据类型')
    return false
  }
  return true
}


// 加载数据类型
const loadDataTypes = async () => {
  try {
    const data = await apiService.getDataTypes()
    dataTypes.value = data.dataTypes || []
  } catch (error) {
    console.error('加载数据类型失败:', error)
  }
}

// 创建表
const createTable = async () => {
  if (!formRef.value) return
  
  // 验证基本信息
  const valid = await formRef.value.validate().catch(() => false)
  if (!valid) return
  
  // 验证列信息
  if (form.columns.length === 0) {
    ElMessage.warning('请至少添加一列')
    return
  }
  
  for (let i = 0; i < form.columns.length; i++) {
    if (!validateColumn(i)) return
  }
  

  
  loading.value = true
  try {

    
    // 从路由参数中取出区域和类型，比如 region=测试村&type=建筑类
    const region = route.query.region || ''
    const type = route.query.type || ''

    // 拼接完整表名
    const fullName = `${region}_${type}_${form.tableName}`

    // 构造请求体
    const tableData = {
      tableName: fullName,
      comment: form.comment,
      columns: form.columns
    }

    
    await apiService.createTable(tableData)
    ElMessage.success(`表 "${form.tableName}" 创建成功`)
    emit('success')
    dialogVisible.value = false
  } catch (error) {
    console.error('创建表失败:', error)
    ElMessage.error('创建表失败')
  } finally {
    loading.value = false
  }
}

// 重置表单
const resetForm = () => {
  Object.assign(form, {
    tableName: '',
    comment: '',
    columns: []
  })
  
  if (formRef.value) {
    formRef.value.resetFields()
  }
}



// 初始化时添加一个空列（不再包含 id）
const initializeForm = () => {
  if (form.columns.length === 0) {
    addColumn()
  }
}


// 监听对话框打开
watch(dialogVisible, (val) => {
  if (val) {
    initializeForm()
  }
})

// 初始化
onMounted(() => {
  loadDataTypes()
})
</script>

<style scoped>
.form-section {
  margin-bottom: 20px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.section-title {
  font-weight: 600;
  color: #303133;
}

.column-options {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.column-tips {
  margin-top: 20px;
  text-align: center;
}

:deep(.el-table .cell) {
  padding: 4px 0;
}

:deep(.el-form-item) {
  margin-bottom: 16px;
}

:deep(.el-card__header) {
  padding: 12px 20px;
  background-color: #f8f9fa;
}

:deep(.el-card__body) {
  padding: 20px;
}
</style>